import chalk from "chalk";
import { getIP } from "./utils";
import { createUrlParams } from "../scripts/urlParams";

const printUrl = (server, ip, urlParams) => {
  let { port } = server.httpServer.address() || {};
  console.log(
    chalk.yellow(`> IP地址: `),
    chalk.cyan(`http://${ip}:${port}/?${urlParams} \n\n`)
  );
  console.log(
    chalk.yellow(`> 本地地址: `),
    chalk.cyan(`http://localhost:${port}/?${urlParams}`)
  );
};

export default function queryPlugin() {
  let ip = getIP();
  let urlParams = createUrlParams();
  return {
    name: "vite-plugin-query",
    configResolved(resolvedConfig) {
      // 存储最终解析的配置
      const command = resolvedConfig.command;
      if (command === "serve") {
        resolvedConfig.preview.open = `?${urlParams}`;
      }
      return resolvedConfig;
    },
    configureServer(server) {
      server.printUrls = () => printUrl(server, ip, urlParams);
    },
  };
}
